#!/user/bin/env python
# -*- coding: utf-8 -*-
# @Software: PyCharm
# @Time : 2022/1/22 13:57
# @Author : ziqi.zhang
# @Version : 
# @Description : 数据库操作类

import pymysql
import configparser
from Common.Config import ReadConfig


class DataBase:
    """数据库操作类"""

    def connect_db(self):
        """连接数据库"""
        conf = configparser.ConfigParser()  # 读取配置文件的实例
        conf.read(ReadConfig().load_config(), encoding='utf8')  # 获取配置文件
        host = conf.get('DataBase', 'host')
        port = int(conf.get('DataBase', 'port'))
        user = conf.get('DataBase', 'user')
        password = conf.get('DataBase', 'password')
        database = conf.get('DataBase', 'database')
        charset = conf.get('DataBase', 'charset')
        return pymysql.connect(host=host, port=port, user=user, password=password, database=database, charset=charset)

    def select_sql(self, sql):
        """查询sql，查"""
        db = DataBase().connect_db()  # 连接数据库
        cursor = db.cursor()  # 创建游标对象
        try:
            cursor.execute(sql)  # 执行sql语句
            result = cursor.fetchall()  # 返回sql的结果集
        except Exception as e:
            print(f'SQL执行失败：{e}')
            result = False
        cursor.close()  # 关闭游标对象
        db.close()  # 关闭数据库连接
        return result

    def alter_sql(self, sql):
        """修改sql，增删改"""
        db = DataBase().connect_db()  # 连接数据库
        cursor = db.cursor()  # 创建游标对象
        try:
            cursor.execute(sql)  # 执行sql语句
            db.commit()  # 提交数据库执行
            result = True
        except Exception as e:
            print(f'SQL执行失败：{e}')
            db.rollback()  # 发生错误就回滚
            result = False
        cursor.close()  # 关闭游标对象
        db.close()  # 关闭数据库连接
        return result
